import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:sph_driver/AppConfig/Config.dart';
import 'package:sph_driver/AppConfig/LocalStorage.dart';
import 'package:sph_driver/RoadLine/AddLine.dart';
import 'package:sph_driver/RoadLine/Editline.dart';
import 'package:sph_driver/RoadLine/RoteOfSource.dart';
import 'package:sph_driver/RoadLine/UpEmptyLine.dart';
import 'package:sph_driver/http/getapi.dart';

import '../AppConfig/RouteAct.dart';
import '../Message/MessageCenter.dart';
import '../http/NoLoadingGetApi.dart';
import '../http/NoLoadingPostApi.dart';
import '../http/api.dart';
import '../l10n/messages.dart';

class RoadLineView extends StatefulWidget {
  const RoadLineView({super.key});

  @override
  State<RoadLineView> createState() => _RoadLineViewState();
}

class _RoadLineViewState extends State<RoadLineView> {
  int isEdit=0;
  Map emptyData={};
  List roadLineData=[];
  List startNameList=[];
  List endNameList=[];
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getEmptyLineAction();
    getRoadLineAction();
  }
  //获取常跑路线信息
  Future<void> getRoadLineAction() async {
    String? drvId =await UserIdManager.getUserID();
    NoLoadinggetApiManager.getData(
      context,
      "api/goods/driver/route/list",
      {
        "id":drvId,
      },
          (responseData) {
            setState(() {
              roadLineData=responseData['data'];
            });

      },
    );

  }
  //获取空车上报信息
  Future<void> getEmptyLineAction() async {
    String? drvId =await UserIdManager.getUserID();
    NoLoadinggetApiManager.getData(
      context, // 上下文对象，用于显示提示信息等
      'api/goods/idle/vehicle/online', // 您的API端点
      {}, // 查询参数，如果没有可以传递null
          (responseData) async {
            setState(() {
              if(responseData['data']!=null)
              emptyData=responseData['data'];
            });
      },
    );

  }
  //删除路线
  void deleRoadLineAct(String id)async{
    String? token = await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));
    dio.post(MyServiceUrl.header + 'api/goods/driver/route/delete',
      data: [
        {"id":id}
      ],
      options: Options(
        sendTimeout: Duration(seconds: 2),
        receiveTimeout: Duration(seconds: 50),
      ),
      onSendProgress: (a, b) => print('send ${a / b}'),
      onReceiveProgress: (a, b) =>
          print('received ${a / b}'),
    )
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(
            r.toString());
        // 获取code和data
        String code = jsonMap['code'].toString();
        if (code == "200") {
          BrnToast.show("删除成功", context, duration: BrnDuration.short,);
          getRoadLineAction();
        } else {
          BrnToast.show(jsonMap['msg'], context);
        }
      });
    }).catchError((error) {
      print(error);
      ;
    });
  }
//删除空车
 void deleEmptyAction(String drvId)async{
   String? token = await TokenManager.getToken();
   dio.interceptors.add(InterceptorsWrapper(
       onRequest: (options, handler) {
         options.headers["satoken"] = token;
         return handler.next(options);
       }
   ));
   dio.post(MyServiceUrl.header + 'api/goods/idle/vehicle/delete',
     data: [
       {"id":emptyData['id']}
     ],
     options: Options(
       sendTimeout: Duration(seconds: 2),
       receiveTimeout: Duration(seconds: 50),
     ),
     onSendProgress: (a, b) => print('send ${a / b}'),
     onReceiveProgress: (a, b) =>
         print('received ${a / b}'),
   )
       .then((r) {
     setState(() {
       print(r);
       Map<String, dynamic> jsonMap = json.decode(
           r.toString());
       // 获取code和data
       String code = jsonMap['code'].toString();
       if (code == "200") {
         BrnToast.show("删除成功", context, duration: BrnDuration.short,);
         emptyData={};
         getEmptyLineAction();
       } else {

         BrnToast.show(jsonMap['msg'], context);
       }
     });
   }).catchError((error) {
     print(error);
     ;
   });


 }
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    var messages = AppLocalizations.of(context)!;
    return  Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title:Text( "常跑路线",style: TextStyle(fontWeight: FontWeight.w300),),
        backgroundColor: Colors.white,
        centerTitle: true,
        actions: [

          Badge(
            // label:Text("1"),
            child:GestureDetector(
              child: Row(
                children: [

                  Image.asset("lib/Images/RoadLine/消息icon.png",width: 16.w,height: 16.h,),
                  SizedBox(width: 10.w,),
                ],
              ),
              onTap: (){
                Navigator.push(context,
                    MaterialPageRoute(builder: (context) {
                      return const MessageCenter(
                      );
                    }));
              },
            ),
          ),
          SizedBox(width: 8.w,),
        ],
      ),
      body: ListView(
        children: [
          SizedBox(height: 8.h,),
      Container(

        margin: EdgeInsets.only(left: 8.w,right: 8.w),
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(10))),
          child: Column(
            children: [
              SizedBox(height: 8.h,),
              Row(
                children: [
                  Image.asset("lib/Images/RoadLine/常跑路线矩形.png",width: 4.w,height: 16.h,),
                  SizedBox(width: 8.w,),
                  Text("空车上报",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                  SizedBox(width: 8.w,),
                  Text("更快找货",style: TextStyle(color: Color.fromRGBO(190, 190, 190, 1),fontSize: 12.sp),),
                ],
              ),
              SizedBox(height: 8.h,),

              Container(
                color: Color.fromRGBO(248, 248, 248, 1),
                height: 1.h,
              ),

            if(emptyData.isEmpty)  SizedBox(height:25.h ,),
              emptyData.isNotEmpty&&emptyData['loadPlace']!=null?
                  GestureDetector(
                    child:  Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            SizedBox(height: 10.h,),
                            Container(
                              // width: screenSize.width-100.w,
                              child:  Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Container(
                                    // width:  screenSize.width-120.w,
                                    child:   Row(
                                      children: [
                                        SizedBox(width:10.w ,),
                                        if(emptyData['loadPlace']['county']==""||emptyData['loadPlace']['county']==null)
                                          Text(emptyData['loadPlace']['province']+" "+emptyData['loadPlace']['city'],style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                                        if(emptyData['loadPlace']['county']!=""&&emptyData['loadPlace']['county']!=null)
                                          Text(emptyData['loadPlace']['city'].toString()+" "+emptyData['loadPlace']['county'].toString(),style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                                        Icon(Icons.trending_flat,color: Colors.black,),
                                        if(emptyData['unloadPlace']['county']==""||emptyData['unloadPlace']['county']==null)
                                          Text(emptyData['unloadPlace']['province']+" "+emptyData['unloadPlace']['city'],style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                                        if(emptyData['unloadPlace']['county']!=""&&emptyData['unloadPlace']['county']!=null)
                                          Text(emptyData['unloadPlace']['city'].toString()+" "+emptyData['unloadPlace']['county'].toString(),style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                                      ],
                                    ),
                                  ),


                                ],
                              ),
                            ),
                            SizedBox(height: 4.h,),
                            Row(
                              children: [
                                SizedBox(width: 10.w,),
                                Text(emptyData['loadTime'].substring(5, emptyData['unloadTime'].length - 6).toString()+" 至 ",style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),),
                                Text(emptyData['unloadTime'].substring(5, emptyData['unloadTime'].length - 6).toString()+" 空车",style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),)
                              ],
                            ),
                          ],
                        ),
                        Row(
                          children: [
                            Icon(Icons.arrow_forward_ios,color: MyColors.hintColor,size: 20,),
                            SizedBox(width: 10.w,),
                          ],
                        )

                      ],
                    ) ,
                    onTap: ()async{
                      final result = await Navigator.push( context, FadeRoute(page:UpEmptyLine(emptyData: emptyData, type: 1,)));
                              if (result != null) {
                                  getEmptyLineAction();
                              }
                    },
                  )
                :
              Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Text("您还未上报空车信息",style: TextStyle(color: Color.fromRGBO(190, 190, 190, 1),fontSize: 12.sp),),
                  GestureDetector(
                    child: Image.asset("lib/Images/RoadLine/去上报Btn.png",width: 113.w,height: 40.h,),
                    onTap: ()async{
                     final result=await  Navigator.push(context, FadeRoute(page: UpEmptyLine(
                       emptyData: emptyData, type: 0,
                     )));
                     if(result !=null){
                       getEmptyLineAction();
                     }
                    },
                  ),
                  SizedBox(height: 10.h,),
                ],
              ),
              SizedBox(height: 8.h,),

            ],
        ),
      ),
          SizedBox(height: 8.h,),
          Container(
            padding: EdgeInsets.only(top: 8.h,right: 8.w),
            margin:EdgeInsets.only(left: 8.w,right: 8.w),
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(10))),

            child: Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [
                        Image.asset("lib/Images/RoadLine/常跑路线矩形.png",width: 4.w,height: 16.h,),
                        SizedBox(width: 8.w,),
                        Text("我的配货路线",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                        SizedBox(width: 8.w,),
                        Text("("+roadLineData.length.toString()+"/10)",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                      ],
                    ),
                    GestureDetector(
                      child:
                      isEdit ==0?
                      Row(
                        children: [
                          Image.asset("lib/Images/RoadLine/编辑.png",width: 20.w,height:20.h,),
                          Text("编辑",style: TextStyle(color: Color.fromRGBO(231, 112, 27, 0.85),fontWeight: FontWeight.w600,fontSize: 14.sp),)
                        ],

                      ):  Row(
                        children: [
                          Image.asset("lib/Images/RoadLine/完成编辑.png",width: 20.w,height:20.h,),
                          Text("完成",style: TextStyle(color: Color.fromRGBO(231, 112, 27, 0.85),fontWeight: FontWeight.w600,fontSize: 14.sp),)
                        ],

                      ),
                      onTap: (){
                        setState(() {
                          if(isEdit==1){
                            isEdit=0;
                          }else{
                            isEdit=1;
                          }

                        });
                      },
                    ),

                  ],
                ),
                SizedBox(height: 8.h,),
                Container(
                  color: Color.fromRGBO(248, 248, 248, 1),
                  height: 1.h,
                ),
                // SizedBox(height: 17.h,),
                ListView.separated(
                  shrinkWrap:true,
                  itemCount: roadLineData.length,
                  itemBuilder: (BuildContext context, int index) {

                    return  Column(
                      children: [
                        SizedBox(height: 8.w,),
                        isEdit==0?
                        GestureDetector(
                          child:  Row(
                            children: [
                              SizedBox(width: 8.w,),
                              Container(
                                constraints: BoxConstraints(
                                  // minWidth: 60.w,
                                  maxWidth:screenSize.width/2.5, // 限制文本最大宽度
                                ),
                                // child: Center(
                                  child:  Text(roadLineData[index]['loadPlace']['county']!=null&&roadLineData[index]['loadPlace']['county']!=""? roadLineData[index]['loadPlace']['city']+" "+roadLineData[index]['loadPlace']['county']:roadLineData[index]['loadPlace']['province']+" "+roadLineData[index]['loadPlace']['city'],
                                    maxLines: 1, // 设置显示的最大行数
                                    overflow: TextOverflow.ellipsis, // 超出部分使用省略号表示
                                    style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                                // ),


                              ),


                              Icon(Icons.trending_flat,color: Colors.black,),
                              Container(
                                constraints: BoxConstraints(
                                  // minWidth: 60.w,
                                  maxWidth:screenSize.width/2.5, // 限制文本最大宽度
                                ),
                                // child:Center(
                                child:  Text(roadLineData[index]['unloadPlace']['county']!=null&&roadLineData[index]['unloadPlace']['county']!=""? roadLineData[index]['unloadPlace']['city']+" "+roadLineData[index]['unloadPlace']['county']:roadLineData[index]['unloadPlace']['province']+" "+roadLineData[index]['unloadPlace']['city'],
                                    maxLines: 1, // 设置显示的最大行数
                                    overflow: TextOverflow.ellipsis, // 超出部分使用省略号表示
                                    style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                                // ),

                              ),
                              SizedBox(width: 4.w,),
                              if(roadLineData[index]['cargoNum']!=null)
                                Badge(label: Text(roadLineData[index]['cargoNum'].toString()),backgroundColor: Colors.red,),
                            ],
                          ),
                          onTap: (){
                            if(roadLineData[index]['cargoNum']!=null)
                              Navigator.push(context, FadeRoute(page: RoteOfSource(
                                loadInfo:roadLineData[index]['loadPlace'], unloadInfo: roadLineData[index]['unloadPlace'],
                              )));

                          },
                        )
                            : Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [

                            Row(
                              children: [
                                SizedBox(width: 8.w,),
                                Container(
                                  constraints: BoxConstraints(
                                    // minWidth: 60.w,
                                    maxWidth:screenSize.width/3.3, // 限制文本最大宽度
                                  ),
                                  child:  Text(roadLineData[index]['loadPlace']['county']!=""? roadLineData[index]['loadPlace']['city']+" "+roadLineData[index]['loadPlace']['county']:roadLineData[index]['loadPlace']['province']+" "+roadLineData[index]['loadPlace']['city'],
                                    maxLines: 1, // 设置显示的最大行数
                                    overflow: TextOverflow.ellipsis, // 超出部分使用省略号表示
                                    style: TextStyle(color: Colors.black,fontSize: 14.sp),),

                                ),
                                Icon(Icons.trending_flat,color: Colors.black,),
                                Container(
                                  constraints: BoxConstraints(
                                    // minWidth: 60.w,
                                    maxWidth:screenSize.width/3.3, // 限制文本最大宽度
                                  ),
                                  child:  Text(roadLineData[index]['unloadPlace']['county']!=""? roadLineData[index]['unloadPlace']['city']+" "+roadLineData[index]['unloadPlace']['county']:roadLineData[index]['unloadPlace']['province']+" "+roadLineData[index]['unloadPlace']['city'],
                                    maxLines: 1, // 设置显示的最大行数
                                    overflow: TextOverflow.ellipsis, // 超出部分使用省略号表示
                                    style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                                ),


                              ],
                            ),
                            Row(
                              children: [
                                GestureDetector(
                                  child: Text("修改",style: TextStyle(color: Color.fromRGBO(231, 112, 27, 0.85),fontSize: 14.sp)),
                                  onTap: () async{
                                 final result=await   Navigator.push( context, FadeRoute(page:EditLine(dataMap: roadLineData[index],)));
                                 if(result!=null){
                                   getRoadLineAction();
                                 }
                                  },
                                ),
                                SizedBox(width: 10.w,),
                                GestureDetector(
                                  child: Text("删除",style: TextStyle(color: Color.fromRGBO(249, 88, 88, 1),fontSize: 14.sp)),
                                  onTap: ()async{
                                    showDialog(
                                      barrierDismissible: false,
                                      context: context,
                                      builder: (BuildContext context) {
                                        return BrnDialog(
                                          titleText: "确定删除该配货路线吗？",
                                          actionsWidget: [
                                            TextButton(
                                              onPressed: () {
                                                Navigator.pop(context);
                                                deleRoadLineAct(roadLineData[index]['id']);
                                              },
                                              child: Text("确定",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
                                            ),
                                            TextButton(
                                              onPressed: () {
                                                Navigator.pop(context);
                                              },
                                              child: Text("取消",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                                            ),
                                          ],
                                        );
                                      },
                                    );

                                  },
                                ),
                              ],
                            )



                          ],
                        ),



                        SizedBox(height: 8.w,),
                      ],
                    );

                  },
                  separatorBuilder: (context, index) { //自定义分割线
                    return   Container(
                      color: Color.fromRGBO(248, 248, 248, 1),
                      height: 1.h,
                    );
                  },


                ),
                SizedBox(height:15.h ,),
                GestureDetector(
                  child: Image.asset("lib/Images/RoadLine/添加路线Btn.png",width: 300.w,height: 40.h,),
                  onTap: ()async {
                    final result =await     Navigator.push( context, FadeRoute(page:AddLine(linesNum: roadLineData.length.toString(),)));

                    if(result !=null){
                      getRoadLineAction();
                    }
                  },
                ),
                SizedBox(height: 10.h,),
              ],

            ),
          ),
        ],
      ),


    );
  }
}
